<template>
  <div class="login">
    <div>
      <h3>后台管理系统</h3>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="adminname">
          <el-input v-model="form.adminname">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="password"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <!-- <el-button type="info">Cancel</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";
// icon 图标按需导入
import { User, Lock } from "@element-plus/icons-vue";
import { Login } from "../service/admin";
export default {
  components: {
    User,
    Lock,
  },
  data() {
    return {
      form: {
        adminname: "",
        password: "",
      },
      rules: {
        adminname: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 5,
            message: "长度应该是3到5之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 4,
            max: 9,
            message: "长度应该是4到9之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      let formEl = this.$refs.form;
      // console.log(formEl);
      if (!formEl) return;
      formEl.validate((valid) => {
        // validate 表单校验方法，
        if (valid) {
          // 表单校验通过，valid是true，否则 valid是false
          console.log("submit!", this.form);
          Login( this.form).then((res) => {
            if (res.code === "200") {  // 少写一个data
              // console.log(res);
              // 把登录后的用户消息存储到仓库里
              this.$store.commit("setUserInfo",res.data) // 传统方法
              this.$router.push("/home")  // 跳转到首页、home页面
            }
          });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  background: rgb(25, 79, 100);
}
.login > div {
  width: 400px;
  height: 200px;
  background: rgba(128, 128, 128, 0.3);
  text-align: center;
  padding: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
}
.login > div > form {
  margin: 0 auto;
}
.login h3 {
  text-align: center;
  color: white;
}
.login button {
  width: 100%;
  margin: 0 auto;
}
</style>
